package com.chuanyang.driverh.mainorder;


import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.chuanyang.driverh.BaseApplication;
import com.chuanyang.driverh.R;
import com.chuanyang.driverh.base.BaseTitleActivity;
import com.chuanyang.driverh.base.OnCustomListener;
import com.chuanyang.driverh.bean.AssignGoodData;
import com.chuanyang.driverh.bean.Waybill;
import com.chuanyang.driverh.mainorder.adapter.AssignGoodsAdapter;
import com.chuanyang.driverh.responseresult.CarTeamMenmberData;
import com.chuanyang.driverh.responseresult.DriverInfoData;
import com.chuanyang.driverh.responseresult.OrderDatailResult;
import com.chuanyang.driverh.responseresult.OrderDetailData;
import com.chuanyang.driverh.responseresult.Result;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.eventbus.RefleshOrderData;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

public class AssignGoodsActivity extends BaseTitleActivity {
    private ArrayList<AssignGoodData> waybillParams;
    private TextView tv_assigingoods_ordernuber;
    private TextView tv_assigingoods_weight;
    private TextView tv_assigingoods_amount;
    private TextView tv_assigingoods_arrange;
    private ListView lv_assigingoods_list;
    private OrderDetailData orderDetail;
    private String orderId;
    private AssignGoodsAdapter assignGoodsAdapter;
    private AssignGoodData assignGoodData;
    private Double totalWeight = new Double(0);
    private DriverInfoData driverinfo;
    private TextView tv_assigingoods_num;
    private TextView tv_assigingoods_resweight;
    private TextView tv_assigingoods_resnum;
    private TextView tv_assigingoods_assweight;
    private TextView tv_assigingoods_assnum;
    private TextView tv_addassign;

    @Override
    protected int getContentResId() {
        return R.layout.order_act_assigngoods;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tv_assigingoods_ordernuber = (TextView) findViewById(R.id.tv_assigingoods_ordernuber);
        tv_assigingoods_weight = (TextView) findViewById(R.id.tv_assigingoods_weight);//重量
        tv_assigingoods_num = (TextView) findViewById(R.id.tv_assigingoods_num);//数量
        tv_assigingoods_resweight = (TextView) findViewById(R.id.tv_assigingoods_resweight);//剩余重量
        tv_assigingoods_resnum = (TextView) findViewById(R.id.tv_assigingoods_resnum);//剩余数量
        tv_assigingoods_assweight = (TextView) findViewById(R.id.tv_assigingoods_assweight);//已分配重量
        tv_assigingoods_assnum = (TextView) findViewById(R.id.tv_assigingoods_assnum);//已分配数量
        //   tv_assigingoods_amount = (TextView) findViewById(R.id.tv_assigingoods_amount);
        //确认部署
        tv_assigingoods_arrange = (TextView) findViewById(R.id.tv_assigingoods_arrange);
        lv_assigingoods_list = (ListView) findViewById(R.id.lv_assigingoods_list);
        View   list_foot = View.inflate(this, R.layout.order_act_assigngoodfoot, null);
        lv_assigingoods_list.addFooterView(list_foot);
        tv_addassign = (TextView) list_foot.findViewById(R.id.tv_assigngoood_add);

    }

    @Override
    protected void initData() {
        setBackImg();
        getTitleTextView().setText("分配货物");
        showActivityLoading();
        driverinfo = BaseApplication.getInstance().getDriverInfo();
        //获取传递过来的订单id
        Intent intent = getIntent();
        orderId = intent.getStringExtra("data");
        waybillParams = new ArrayList();
        assignGoodsAdapter = new AssignGoodsAdapter(this, waybillParams);
        lv_assigingoods_list.setAdapter(assignGoodsAdapter);

        getOrderdatail();
    }

    @Override
    protected void initListener() {
        tv_assigingoods_arrange.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //此处注释的部分是判断单次分配，货物必须分配完全的限制，目前暂时不用先注释
                totalWeight=0.0;
                Waybill waybill = new Waybill();
//                if (waybillParams.size() > 0) {
//                    for (int i = 0; i < waybillParams.size(); i++) {
//                        Double assignWeight = waybillParams.get(i).getAssignWeight();
//                        totalWeight = totalWeight + assignWeight;
//                    }
//                    if (orderDetail.getGoodsSumWeight() > totalWeight) {
//                        showMsg("货物未分配完全");
//                        return;
//                    }
                if(waybillParams.size()==0)
                {
                    PrintUtil.toast(activityContext,"您当前还未分配货物！");
                    return;
                }
                waybill.setWaybillParams(waybillParams);
                waybill.setOrderId(orderId);
                postAssignInfo(waybill);
                //   }
            }
        });
        tv_addassign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //如果货物已经分配完成，不再进行分配
                /*if (orderDetail!=null ){
                    if (orderDetail.getSurplusSumNum()<=0 ||Double.valueOf(orderDetail.getSurplusSumWeight())<=0){
                        PrintUtil.toast(activityContext,"货物已经分配完毕。");
                        return;
                    }
                }*/

                if (driverinfo != null && driverinfo.getFleet() != null) {
                    Intent intent = new Intent(AssignGoodsActivity.this, CarTeamMenmberActivity.class);
                    intent.putExtra("index", "1");
                    intent.putExtra("data", waybillParams);
                    startActivityForResult(intent, 1);
                } else {
                    PrintUtil.toast(activityContext,"您没有车队，无法分配运单！");
                }
            }
        });


        assignGoodsAdapter.setOnCustomListener(new OnCustomListener() {
            @Override
            public void onCustomerListener(View v, int position) {
                switch (v.getId()) {
                    case R.id.tv_assign_delete:
                        //删除分配时  需要加上删除已分配的货物重量
                        addAssignWeight(waybillParams.get(position));
                        waybillParams.remove(position);
                        assignGoodsAdapter.notifyDataSetChanged();
                        break;
                    case R.id.tv_assign_change:
                        //  Waybill waybill = new Waybill();
                        //  waybill.setWaybillParams(waybillParams);
                        //Intent intent = new Intent(AssignGoodsActivity.this, AssignGoodsDetailActivity.class);
                        Intent intent = new Intent(AssignGoodsActivity.this, AssignGoodsDetailNewActivity.class);
                        assignGoodData = waybillParams.get(position);
                        assignGoodData.setIndex(position);
                        intent.putExtra("AssignGoodData", assignGoodData);
                        intent.putExtra("OrderDetailData", orderDetail);
                        intent.putExtra("type", "1");//修改
//                        intent.putExtra("Waybill", waybill);
                        startActivityForResult(intent, 2);
                        break;
                }

            }
        });
    }




    private void getOrderdatail() {
        DialogUtil.showLoadingDialog(activityContext,"加载中...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("orderId", orderId);
        params.put("driverId", SharedPrefUtil.getUserId());

        MyHttpUtil.selectOrderMsgById(activityContext,params, new MyCallback<OrderDatailResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(OrderDatailResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    hideActivityLoading();
                    orderDetail = result.getData();
                    fillView(orderDetail);
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }

            }
        });
    }

    private void postAssignInfo(Waybill waybill) {
        DialogUtil.showLoadingDialog(activityContext,"加载中...");
        Map<String,String> params=new HashMap<String, String>();

        MyHttpUtil.AllotWaybill(activityContext,waybill, new MyCallback<Result>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    PrintUtil.toast(activityContext,"货物分配成功");
                    EventBus.getDefault().post(new RefleshOrderData(1));
                    finish();
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }

            }
        });
    }


    private void fillView(OrderDetailData data) {
        tv_assigingoods_ordernuber.setText(data.getOrderNo());
        if (data.getGoodsSumWeight() != 0) {
            tv_assigingoods_weight.setText(data.getGoodsSumWeight() + "t");
        } else {
            tv_assigingoods_weight.setText("---");
        }
        if (data.getGoodsSumNum() !=0) {
            tv_assigingoods_num.setText(data.getGoodsSumNum() + "");
        }
        else {
            tv_assigingoods_num.setText("---");

        }
        if(data.getSurplusSumWeight()!=0)
        {
            tv_assigingoods_resweight.setText(data.getSurplusSumWeight()+"t");
            double assignweight=data.getGoodsSumWeight()-data.getSurplusSumWeight();
            tv_assigingoods_assweight.setText(assignweight+"t");
        }
        else {
            tv_assigingoods_resweight.setText("---");
            tv_assigingoods_assweight.setText("---");


        }
        if(data.getSurplusSumNum()!=0)
        {
            tv_assigingoods_resnum.setText(data.getSurplusSumNum()+"");
            int assignnum=(int)(data.getGoodsSumNum()-data.getSurplusSumNum());
            tv_assigingoods_assnum.setText(assignnum+"");

        }
        else {
            tv_assigingoods_resnum.setText("---");
            tv_assigingoods_assnum.setText("---");

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1) { //添加分配时
            CarTeamMenmberData carteammenmber = (CarTeamMenmberData) data.getSerializableExtra("CarTeamMenmberData");
            assignGoodData = new AssignGoodData();
            assignGoodData.setDriverId(carteammenmber.getDriverId());
//            assignGoodData.setOrderId(Integer.parseInt(orderId));
            assignGoodData.setDriverName(carteammenmber.getUsername());
            assignGoodData.setDriverImage(carteammenmber.getUserImage());
            assignGoodData.setLoadWeight(carteammenmber.getCapacity());
            assignGoodData.setPlateNumber(carteammenmber.getPlateNumber());
            //  Intent intent = new Intent(AssignGoodsActivity.this, AssignGoodsDetailActivity.class);
            Intent intent = new Intent(AssignGoodsActivity.this, AssignGoodsDetailNewActivity.class);
            intent.putExtra("AssignGoodData", assignGoodData);
            intent.putExtra("OrderDetailData", orderDetail);
            intent.putExtra("type", "2");//添加
            startActivityForResult(intent, 2);
        } else if (resultCode == 2) {//返回分配结果(此时表示是添加分配)

            assignGoodData = (AssignGoodData) data.getSerializableExtra("AssignGoodData");
//            if (waybillParams.size() > 0)
//            {
//
//                for (int i = 0; i < waybillParams.size(); i++) {
//                    if (waybillParams.get(i).getDriverId().equals(assignGoodData.getDriverId())) {
//
//                        addAssignWeight(waybillParams.get(i));
//                        waybillParams.remove(i); //删除分配时  需要加上删除已分配的货物重量
//                    }
//                }
//
//
//            }
            //分配成功后需要减掉分配的重量
            lostAssignWeight(assignGoodData);
            waybillParams.add(assignGoodData);
            assignGoodsAdapter.notifyDataSetChanged();


        }
        else if (resultCode == 3)//此时表示是修改分配
        {
            assignGoodData = (AssignGoodData) data.getSerializableExtra("AssignGoodData");
            addAssignWeight(waybillParams.get(assignGoodData.getIndex()));
            waybillParams.remove(assignGoodData.getIndex()); //删除分配时  需要加上删除已分配的货物重量
            //分配成功后需要减掉分配的重量
            lostAssignWeight(assignGoodData);
            waybillParams.add(assignGoodData);
            assignGoodsAdapter.notifyDataSetChanged();

        }


    }



    private void addAssignWeight(AssignGoodData assign) {
        List<OrderDetailData.DetailListBean> detailList = orderDetail.getDetailList();
        List<AssignGoodData.WaybillDetailsData> assignList = assign.getWaybillDetails();
        for (int i = 0; i < detailList.size(); i++) {
            OrderDetailData.DetailListBean goodDetail = detailList.get(i);

            for (int a = 0; a < assignList.size(); a++) {
                AssignGoodData.WaybillDetailsData assignDetail = assignList.get(a);
                if (goodDetail.getOrderDetailId() == assignDetail.getOrderdetailId()) {
                    if (!TextUtils.isEmpty(assignDetail.getDetailsWeight())) {
                        //   goodDetail.setGoodsWeight((Double.parseDouble(goodDetail.getGoodsWeight()) + Double.parseDouble(assignDetail.getDetailsWeight())) + "");
                        goodDetail.setSurplusWeight((Double.parseDouble(goodDetail.getSurplusWeight()) + Double.parseDouble(assignDetail.getDetailsWeight())) + "");
                    }
                }
            }
            detailList.set(i, goodDetail);
        }
        orderDetail.setDetailList(detailList);
    }


    private void lostAssignWeight(AssignGoodData assignGoodData) {
        List<OrderDetailData.DetailListBean> detailList = orderDetail.getDetailList();
        List<AssignGoodData.WaybillDetailsData> assignList = assignGoodData.getWaybillDetails();
        for (int i = 0; i < detailList.size(); i++) {
            OrderDetailData.DetailListBean goodDetail = detailList.get(i);
            for (int a = 0; a < assignList.size(); a++) {
                AssignGoodData.WaybillDetailsData assignDetail = assignList.get(a);
                if (goodDetail.getOrderDetailId() == assignDetail.getOrderdetailId()) {
                    if (!TextUtils.isEmpty(assignDetail.getDetailsWeight())) {
                        //  goodDetail.setGoodsWeight((Double.parseDouble(goodDetail.getGoodsWeight()) - Double.parseDouble(assignDetail.getDetailsWeight())) + "");
                        goodDetail.setSurplusWeight((Double.parseDouble(goodDetail.getSurplusWeight()) - Double.parseDouble(assignDetail.getDetailsWeight())) + "");
                    }
                }
            }
            detailList.set(i, goodDetail);
        }
        orderDetail.setDetailList(detailList);
    }
}
